package com.hnust.util;

import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.imageio.ImageIO;

import com.hnust.config.YamlReader;
import com.spire.doc.Document;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import com.spire.doc.interfaces.ICompositeObject;
import com.spire.doc.interfaces.IDocumentObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PictureIO {

	public static void doPic(Document document) throws IOException {
		//创建Queue对象
		Queue nodes = new LinkedList();
		nodes.add(document);
		//创建List对象
		List images = new ArrayList();
		List<String> imagesNames = new ArrayList<>();
		List<Float> widthList = new ArrayList();
		List<Float> hightList = new ArrayList();
		int ai = 1;
		int con = 0;
		int param_num = 0;
		File picdir = new File(System.getProperty("user.dir") + "/assets/pictures");
		if (!picdir.exists()) {
			picdir.mkdir();
		}
		while (nodes.size() > 0) {
			ICompositeObject node = (ICompositeObject) nodes.poll();
			if (param_num == 0 && ai++ == 3) {
				param_num = 1;
			}

			int exist = 0;

			for (int i = 0; i < node.getChildObjects().getCount(); i++) {
				IDocumentObject child = node.getChildObjects().get(i);
				if (param_num != 0) {
					exist = 1;
				}
				if (child instanceof ICompositeObject) {
					nodes.add((ICompositeObject) child);
					//获取 图片并添加到list
					if (child.getDocumentObjectType() == DocumentObjectType.Picture) {
						DocPicture picture = (DocPicture) child;
						float w = picture.getWidth();
						float h = picture.getHeight();
						picture.setWidth(w);
						picture.setHeight(h);

						images.add(picture.getImage());
						String name = IDUtil.getPrimaryKey();
//						TextRange text = (TextRange) node.getChildObjects().get(i);
						TextRange text = new TextRange(document);
						String picPath = "http://" + YamlReader.instance.getValueByKey("pic.url") + ":" + YamlReader.instance.getValueByKey("pic.port") + "/pic/";
						imagesNames.add(name);
						text.setText(("<img =\"width: "+(String.format("%.2f",picture.getWidth()*1.5))+"px;height: "+(String.format("%.2f",picture.getHeight()*1.5))+"px;\" src=\"" + picPath + name+".png\"/>").replace(" ","&778604985"));
//						document.replace(text.getText(), "<img src=\"" + picPath + name+".png\"/>" + text.getText(), true, false);
						node.getChildObjects().insert(i, text);
						node.getChildObjects().remove(child);
					}
				}
			}
		}
		//将图片保存为PNG格式
		for (int i = 0; i < images.size(); i++) {
			File file = new File(picdir +"/"+ imagesNames.get(i)+".png");
			ImageIO.write((RenderedImage) images.get(i), "PNG", file);
		}
	}
}